layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
})
layui.use(['utilObj', 'element', 'layer', 'laypage', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        utilObj = layui.utilObj,
        element = layui.element,
        laypage = layui.laypage,
        table = layui.table;
    var unReadUrl = "cms/message/findUnreadByConditionsPage";
    var hasReadUrl = "cms/message/findhHasreadByConditionsPage";
    var markReadUrl = "/cms/message/sendAllReadMessage";
    var unReadMessages = [];

    var unReadPage = {
        getData: function (pageIndex) {
            var user = localStorage.getItem("user");
            if (user) {
                user = JSON.parse(user);
            }
            var data = {
                userId: user.userId,
                pageIndex: pageIndex - 1,
                pageSize: utilObj.pageSize
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: unReadUrl,
                type: "POST",
                data: data,
                success: function (data) {
                    if (data && data.content) {
                        unReadMessages = data.content;
                        unReadPage.tableIns = table.render({
                            elem: '#unreadMessageList',
                            cellMinWidth: 95,
                            page: false,
                            height: "full-175",
                            limit: utilObj.pageSize,
                            id: "unreadMessageListTable",
                            cols: [[
                                {
                                    field: 'content',
                                    title: '消息内容',
                                    align: "center"
                                },
                                {
                                    field: 'createTime',
                                    title: '创建时间',
                                    align: 'center',
                                    templet: function (d) {
                                        return convertDateLongToString(d.createTime);
                                    }
                                },
                                {
                                    title: '操作',
                                    width: '20%',
                                    templet: '#messageListBar',
                                    fixed: "right",
                                    align: "center"
                                }
                            ]],
                            data: data.content
                        });
                        $('#messsage-unread').text(data.totalElements);
                        laypage.render({
                            elem: 'unreadPagination',
                            curr: pageIndex,
                            count: data.totalElements, //数据总数
                            limit: utilObj.pageSize, //每页显示条数
                            // layout: ['prev', 'next'],
                            jump: function (obj, first) {
                                unReadPage.current = obj.curr;
                                if (!first) {
                                    unReadPage.getData(obj.curr);
                                }
                                console.log(obj);
                            }
                        });
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                }
            });
        },
        markAsRead: function (messageIds) {
            var user = localStorage.getItem("user");
            if (user) {
                user = JSON.parse(user);
            }
            // "Required String parameter 'messageIdList' is not present"
            var data = {
                userId: user.userId,
                messageIdList: messageIds
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: markReadUrl,
                type: "POST",
                data: data,
                success: function (data) {
                    utilObj.hideLoading();
                    if (data) {
                        //标记消息已读成功
                        unReadPage.getData(1);
                        readPage.getData(1)
                    }
                },
                error: function (err) {
                    console.log(err);
                    utilObj.hideLoading();
                }
            });
        },
        init: function () {
            unReadPage.getData(1);
            table.on('tool(unreadMessageList)', function (obj) {
                var layEvent = obj.event,
                    data = obj.data;
                if (layEvent === 'markRead') {
                    unReadPage.markAsRead(data.id);
                }
            });
        }
    };
    unReadPage.init();

    var readPage = {
        getData: function (pageIndex) {
            var user = localStorage.getItem("user");
            if (user) {
                user = JSON.parse(user);
            }
            var data = {
                userId: user.userId,
                pageIndex: pageIndex - 1,
                pageSize: utilObj.pageSize
            };
            utilObj.showLoading();
            utilObj.ajax({
                url: hasReadUrl,
                type: "POST",
                data: data,
                success: function (data) {
                    if (data && data.content) {
                        readPage.tableIns = table.render({
                            elem: '#readMessageList',
                            cellMinWidth: 95,
                            page: false,
                            height: "full-125",
                            limit: utilObj.pageSize,
                            id: "readMessageListTable",
                            cols: [
                                [{
                                    field: 'content',
                                    title: false,
                                    minWidth: 100,
                                    align: "center"
                                },
                                    {
                                        field: 'createTime',
                                        title: false,
                                        align: 'center',
                                        templet: function (d) {
                                            return convertDateLongToString(d.createTime);
                                        }
                                    }
                                ]
                            ],
                            data: data.content
                        });
                        $('#message-read').text(data.totalElements);
                        laypage.render({
                            elem: 'readPagination',
                            curr: pageIndex,
                            count: data.totalElements, //数据总数
                            limit: utilObj.pageSize, //每页显示条数
                            // layout: ['prev', 'next'],
                            jump: function (obj, first) {
                                readPage.current = obj.curr;
                                if (!first) {
                                    readPage.getData(obj.curr);
                                }
                                console.log(obj);
                            }
                        });
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                }
            });
        },
        init: function () {
            readPage.getData(1);
        }
    };
    readPage.init();

    element.on('tab(docDemoTabBrief)', function (data) {
        console.log(data);
        if (data.index === 0) {
            $('.btn_markread').show();
        } else {
            $('.btn_markread').hide();
        }
    });

    //触发事件
    var active = {
        tabAdd: function () {
            //新增一个Tab项
            element.tabAdd('demo', {
                title: '新选项' + (Math.random() * 1000 | 0) //用于演示
                ,
                content: '内容' + (Math.random() * 1000 | 0),
                id: new Date().getTime() //实际使用一般是规定好的id，这里以时间戳模拟下
            })
        },
        tabDelete: function (othis) {
            //删除指定Tab项
            element.tabDelete('demo', '44'); //删除：“商品管理”

            othis.addClass('layui-btn-disabled');
        },
        tabChange: function () {
            //切换到指定Tab项
            element.tabChange('demo', '22'); //切换到：用户管理
        }
    };

    //全部标记为已读
    $('.btn_markread').on('click', function () {
        var messageIds = [];
        for (var i = 0; i < unReadMessages.length; i++) {
            messageIds.push(unReadMessages[i].id);
        }
        var paramIds = messageIds.join(",");
        unReadPage.markAsRead(paramIds);
    });

    $('.site-demo-active').on('click', function () {
        var othis = $(this),
            type = othis.data('type');
        active[type] ? active[type].call(this, othis) : '';
    });


    function convertDateLongToString(str) {
        if (str == "" || str == null || str == undefined) {
            return "";
        } else {
            return new Date(str).format('yyyy-MM-dd hh:mm:ss');
        }
    }

    Date.prototype.format = function (format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

})